package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import com.sun.tracing.ProviderName;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping()
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        //删除某一类菜品的缓存数据
        String key= "dish_"+dishDto.getCategoryId()+"_"+dishDto.getStatus();
        redisTemplate.delete(key);

        //删除所有的菜品缓存数据
        //Set keys = redisTemplate.keys("dish_*");
        //redisTemplate.delete(keys);

        return R.success("添加菜品成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //条件构造器
        LambdaQueryWrapper<Dish> LQW = new LambdaQueryWrapper<>();
        //添加过滤条件
        LQW.like(name != null, Dish::getName, name);
        //添加排序
        LQW.orderByDesc(Dish::getUpdateTime);
        //执行分页查询
        dishService.page(pageInfo, LQW);
        //对象拷贝,将pageInfo的数据拷给dishDtoPage,忽略records
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category byId = categoryService.getById(categoryId);
            String name1 = byId.getName();
            dishDto.setCategoryName(name1);
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    @GetMapping("{id}")
    public R<DishDto> get(@PathVariable Long id) {

        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        //删除某一类菜品的缓存数据
        String key= "dish_"+dishDto.getCategoryId()+"_"+dishDto.getStatus();
        redisTemplate.delete(key);

        //删除所有的菜品缓存数据
        //Set keys = redisTemplate.keys("dish_*");
        //redisTemplate.delete(keys);
        return R.success("菜品修改成功");
    }

    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable int status, @RequestParam("ids") List<Long> ids) {
        log.info("需要修改的菜品为:{}", ids.toString());
        List<Dish> dishes = dishService.listByIds(ids);
        for (Dish dish : dishes) {
            dish.setStatus(status);
        }
        dishService.updateBatchById(dishes);
        return R.success("销售状态修改成功");
    }


    @DeleteMapping
    @Transactional
    public R<String> delete(@RequestParam("ids") List<Long> ids) {
        //菜品id集合
        List<Dish> dishes = dishService.listByIds(ids);
        //根据菜品id查询出来的口味id集合

//        dishFlavorService.get

        //有未停售的菜品禁止删除
//        for (Dish dish : dishes) {
//            if (dish.getStatus() == 1) {
//                return R.error("不要用你的技术挑战我的耐心");
//            }
//        }
//             dishService.removeByIds(ids);
        //如果有在售的就删除停售到,保留在售的
        for (Dish dish : dishes) {
            if (dish.getStatus().equals(0)) {
                dishService.removeById(dish.getId());
                LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
                lqw.eq(DishFlavor::getDishId, dish.getId());
                dishFlavorService.remove(lqw);
            }
        }

        return R.success("删除成功!");
    }

    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        List<DishDto> dishDtoList = null;
        //查询redis缓存数据,找到菜品信息返回回去,没有就执行原代码,最后将查询出来的数据添加到缓存数据中
        //1.动态获取redis的key
        //1.1将分类id和status拼接起来作为缓存的key
        String key = "dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        //将缓存查询出来的数据赋值给集合,有数据就直接返回,没有就执行原代码
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtoList !=null){
            return R.success(dishDtoList);
        }

        //构造查询条件
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dish.getCategoryId() != null,
                Dish::getCategoryId, dish.getCategoryId());
        //添加条件,查询状态为1(启售状态)的菜品
        lqw.eq(Dish::getStatus, 1);
        //添加排序条件
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(lqw);
        dishDtoList = list.stream().map(item -> {
            DishDto dishDto = new DishDto();
            //对象拷贝
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //根据当前菜品id查询口味
            Long itemId = item.getId();
            LambdaQueryWrapper<DishFlavor> lqw2 = new LambdaQueryWrapper<>();
            lqw2.eq(DishFlavor::getDishId, itemId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lqw2);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());
        //缓存没查到执行原代码,将查询出来的数据添加到缓存中
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);

        return R.success(dishDtoList);
    }


}
